package cn.com.lsjz.nursemanager.service.system;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import cn.com.lsjz.commons.utils.UpdateTool;
import cn.com.lsjz.nursemanager.model.system.SysOperation;
import cn.com.lsjz.nursemanager.repository.system.SysOperationRepository;

@Service
public class SysOperationServiceImpl implements SysOperationService {

	@Autowired
	private SysOperationRepository sysOperationRepository; ;
	
	@Override
	public List<SysOperation> loadModuleByUserId(String userId) {
		return sysOperationRepository.loadByUserId(userId);
	}

	@Override
	public List<SysOperation> loadModuleByParentId(Integer parentModuleId) {
		return sysOperationRepository.getByParentOperationIdOrderBySortIndex(parentModuleId);
	}

	@Override
	public List<SysOperation> loadParentModule() {
		return sysOperationRepository.loadParentModule();
	}

	@Override
	public SysOperation addModule(SysOperation moduleDict) {
		moduleDict.setCreateTime(new Date());
		moduleDict.setActive(1); // 默认启用
		if(moduleDict.getParentOperationId() == null) {
			moduleDict.setParentOperationId(-1);
		}else {
			if(moduleDict.getSortIndex() == null)
				moduleDict.setSortIndex(0);
			if(moduleDict.getDeptShow() == null)
				moduleDict.setDeptShow(1);
			if(moduleDict.getPatShow() == null)
				moduleDict.setPatShow(1);
		}
		return sysOperationRepository.save(moduleDict);
	}

	@Override
	public SysOperation editModule(SysOperation moduleDict) {
		SysOperation module = sysOperationRepository.findOne(moduleDict.getOperationId());
		UpdateTool.copyNullProperties(module, moduleDict);
		moduleDict.setUpdateTime(new Date());
		return sysOperationRepository.save(moduleDict);
	}

	@Override
	public SysOperation getModuleById(Integer moduleId) {
		return sysOperationRepository.findOne(moduleId);
	}

	@Override
	public void delModule(Integer moduleId) {
		sysOperationRepository.delete(moduleId);
	}

	@Override
	public void activeModule(Integer moduleId, Integer active) {
		sysOperationRepository.updateByHql("update ModuleDict m set m.active = ?1 where m.operationId = ?2"
							, active
							, moduleId); 
	}

	@Override
	public List<SysOperation> loadModuleList() {
		return  sysOperationRepository.findAll(new Sort("sortIndex"));
	}

}
